package com.example.homework.h2021_04_28.network;

import android.util.Log;

import com.example.homework.h2021_04_28.network.adapter.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by jbwl on 2018/10/10 17:47.
 */

public class RetrofitFactory {
    private static RetrofitFactory mRetrofitFactory;
    private static ApiService mApiservice;
    private static Gson gson;

    private RetrofitFactory() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(message -> Log.w("OKHTTP", message));
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder().
                connectTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS).
                readTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS).
                writeTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)
                //是否在连接失败后尝试再次连接
                .retryOnConnectionFailure(true)
                //添加拦截器
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        Request request = chain.request();
//                        Request.Builder builder = request.newBuilder();
////                        request.url().newBuilder().addQueryParameter("token", CKApplication.token);
////                        request.url().newBuilder().addQueryParameter("userid", String.valueOf(CKApplication.userId));
////                        chain.proceed(request);
////                        Log.e("requestUrl",request.url().toString());
////                        Log.e("requestUrl",request.url().scheme());
////                        if (CDApplication.getToken()==null || CDApplication.getToken().equals("")){
////
////                        }
//                        String url = request.url().toString();
//                        if (url.contains("login") || url.contains("resetpwd")) {
//                            //添加头部信息，意味着此请求为form表单格式的请求
//                            builder.addHeader("Content-Type", "application/x-www-form-urlencoded");
//                        }
////                        String token = SpUtil.getStringSF(BaseAppApplication.getIns()
////                                , TOKEN);
////                        Log.e("==============>TOKEN", "intercept: " + token);
////                        builder.addHeader("access_token", token);
//                        Response response = chain.proceed(request);
//                        return response;
//                    }
//                })
                .addInterceptor(httpLoggingInterceptor)
                .build();
        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(ApiService.BaseUrl)
                .addConverterFactory(GsonConverterFactory.create(buildGson()))//添加gson转换器
                .client(mOkHttpClient).build();
        mApiservice = mRetrofit.create(ApiService.class);
    }

    public static RetrofitFactory getInstance() {
        if (mRetrofitFactory == null) {
            synchronized (RetrofitFactory.class) {
                if (mRetrofitFactory == null) mRetrofitFactory = new RetrofitFactory();
            }
        }
        return mRetrofitFactory;
    }

    /**
     * 增加后台返回""和"null"的处理
     * 1.int=>0
     * 2.double=>0.00
     * 3.long=>0L
     *
     * @return
     */
    public static Gson buildGson() {
        if (gson == null) {
            gson = new GsonBuilder()
                    .registerTypeAdapter(Integer.class, new IntegerDefaultAdapter())
                    .registerTypeAdapter(int.class, new IntegerDefaultAdapter())
                    .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                    .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                    .registerTypeAdapter(Long.class, new LongDefault0Adapter())
                    .registerTypeAdapter(long.class, new LongDefault0Adapter())
                    .registerTypeAdapter(String.class, new StringNullAdapter())
                    .create();
        }
        return gson;
    }

    public ApiService API() {
        return mApiservice;
    }
}
